import { ref, watch } from 'vue'
import type { App } from 'vue'
// 导入主题配置
import { themes, themeConfig } from '@/themes'

export type ThemeName = keyof typeof themes
export type ThemeServiceType = ThemeService

class ThemeService {
  private themeList: ThemeName[] = Object.keys(themes) as ThemeName[]
  private themeConfig = themeConfig
  private currentTheme: ThemeName = this.themeList[0]
  private themeRef = ref<ThemeName>(this.currentTheme)

  constructor() {
    // 从localStorage加载主题偏好
    const savedTheme = localStorage.getItem('theme') as ThemeName | null
    if (savedTheme && themes[savedTheme]) {
      this.currentTheme = savedTheme
      this.themeRef.value = savedTheme
    }

    // 监听主题变化
    watch(this.themeRef, (newTheme) => {
      this.setTheme(newTheme)
    })

    // 初始设置主题
    this.setTheme(this.currentTheme)
  }

  /**
   * 设置主题
   * @param themeName 主题名称
   */
  setTheme(themeName: ThemeName): void {
    if (!themes[themeName]) {
      console.warn(`Theme ${themeName} does not exist`)
      return
    }

    // 更新当前主题
    this.currentTheme = themeName
    this.themeRef.value = themeName

    // 保存到localStorage
    localStorage.setItem('theme', themeName)

    // 更新CSS变量
    this.updateCssVariables(themeName)

    // 更新类名
    this.themeList.forEach((theme) => {
      if (theme === themeName) {
        document.documentElement.classList.add(theme)
      } else {
        document.documentElement.classList.remove(theme)
      }
    })
  }

  /**
   * 更新CSS变量
   * @param themeName 主题名称
   */
  private updateCssVariables(themeName: ThemeName): void {
    const theme = themes[themeName]
    if (!theme || !theme.colors) return

    // 设置CSS变量
    Object.entries(theme.colors).forEach(([key, value]) => {
      document.documentElement.style.setProperty(`--colors-${key}`, value as string)
    })
  }

  /**
   * 获取当前主题
   */
  getCurrentTheme(): ThemeName {
    return this.currentTheme
  }

  /**
   * 获取主题引用
   */
  getThemeRef() {
    return this.themeRef
  }

  /**
   * 切换到下一个主题
   */
  switchToNextTheme(): void {
    const themeNames = Object.keys(themes) as ThemeName[]
    const currentIndex = themeNames.indexOf(this.currentTheme)
    const nextIndex = (currentIndex + 1) % themeNames.length
    this.setTheme(themeNames[nextIndex])
  }

  /**
   * 获取主题配置
   */
  getThemeConfig(themeName: ThemeName) {
    return this.themeConfig[themeName]
  }

  /**
   * 获取主题列表
   */
  getThemeList() {
    return this.themeList
  }
}

// 创建主题服务实例
const themeService = new ThemeService()

export default themeService

export function provideThemeService(app: App) {
  app.provide('themeService', themeService)
}
